﻿using System;
using System.Windows.Input;
using JetBrains.Annotations;

namespace esquireclockscreensaver.Utils
{
    internal sealed class GenericCommand : ICommand
    {
        private readonly Action<object> _execute;
        private readonly Func<object,bool> _canExecute;

        public GenericCommand([NotNull] Action execute, Func<bool> canExecute = null):this(_=>execute(),_=>canExecute.With(x=>x(), true))
        {
            if (execute == null)
            {
                throw new ArgumentNullException("execute");
            }
        }

        public GenericCommand([NotNull] Action<object> execute, Func<object,bool> canExecute = null)
        {
            if (execute == null)
            {
                throw new ArgumentNullException("execute");
            }
            _execute = execute;
            _canExecute = canExecute;
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute.With(x => x(parameter), true);
        }

        public event EventHandler CanExecuteChanged;

        public void OnCanExecuteChanged(EventArgs e)
        {
            var handler = CanExecuteChanged;
            if (handler != null) handler(this, e);
        }
    }
}
